<?php

class Zend_View_Helper_PageTitle
{

	/**
	 * @var string
	 */
	private $_delim = ' | ';

	/**
	 * @return string
	 */
	public function pageTitle()
	{
		$titles = $this->_getPageTitles();
		if(Zend_Registry::isRegistered('substitutePageTitle')) {
			array_pop($titles);
			$pageTitle = Zend_Registry::get('substitutePageTitle');
			if(is_array($pageTitle)) {
				foreach($pageTitle AS $pt) {
					$titles[] = htmlspecialchars($pt);
				}
			} else {
				$titles[] = Zend_Registry::get('substitutePageTitle');
			}
		}
		return $this->_render($titles);
	}

	/**
	 * @param array $titles
	 * @return string
	 */
	private function _render(array $titles)
	{
		$titles = array_reverse($titles);
		return sprintf('<title>%s</title>', implode($this->_delim, $titles));
	}

	/**
	 * @return array
	 */
	private function _getPageTitles()
	{
		$pageId = WSB_Frontend::getInstance()->getPageId();
		$pageTree = WSB_Node_Page::getBranch($pageId);
		$titles = array();
		while($pageTree->hasParent()) {
			$titles[] = htmlspecialchars($pageTree->title);
			$pageTree = $pageTree->getParent();
		}
		$titles[] = htmlspecialchars($pageTree->title);
		return array_reverse($titles);
	}

}